/*
 * @lc app=leetcode.cn id=653 lang=typescript
 *
 * [653] 两数之和 IV - 输入 BST
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findTarget(root: TreeNode | null, k: number): boolean {
  const nums = [];
  // 中序遍历，得到有序序列
  const inorder = (node: TreeNode | null) => {
    if (node === null) return;
    inorder(node.left);
    nums.push(node.val);
    inorder(node.right);
  };

  inorder(root);
  // 在一个有序序列中找到2数之和为k
  let l = 0;
  let r = nums.length - 1;
  while (l < r && nums[l] + nums[r] - k !== 0) {
    if (nums[l] + nums[r] < k) {
      l++;
    } else {
      r--;
    }
  }

  return l < r;
}
// @lc code=end
